<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
	<title>商品信息管理</title>
	<meta name="decorator" content="default"/>
	<style type="text/css">
		#productModul li a{padding-top: 0px; padding-bottom: 0px;}
	</style>
	<script type="text/javascript">
		var remarksEditor
		KindEditor.ready(function(K) {
			if($('textarea[name="remarks"]')){
				remarksEditor = K.create('textarea[name="remarks"]', {
					cssPath : '<%=basePath %>/static/kindeditor/plugins/code/prettify.css',
					uploadJson : '<%=basePath %>/kindeditor/upload',
					allowFileManager : false,
					allowImageRemote : false,
					formatUploadUrl : false,
					cssPath:"<%=basePath %>/static/front/css/kindeditoriframe-user.css",
					afterCreate : function() {
						var self = this;
						K.ctrl(document, 13, function() {
							self.sync();
							//document.forms['example'].submit();
						});
						K.ctrl(self.edit.doc, 13, function() {
							self.sync();
							//document.forms['example'].submit();
						});
					}
				});
				prettyPrint();
			}
		});
		var $pro_property;//商品属性0实体商品，1虚拟商品
		$(document).ready(function() {
			if('${product.logoUrl }'==''){
				$("#cutPhoto").css("display", "none");
			}
			if('${product.proProperty }'==''){
				$pro_property = 0;
			}else{
				$pro_property = ${product.proProperty }-0;
			}
			//默认加载商品信息
			showInfo(0);
			if('${product.stockState }'=='1'){
				showOrHideStock(1);
			}else{
				$("div[id='parameter']").each(function(){
					$(this).hide();
				});
			}
			//if('${product.openState }'=='1'){
			//	$('input[type="text"],input[type="radio"],input[type="checkbox"],select,textarea,a',$('form[id="inputForm"]')).attr('readonly',true); 
			//	$('input[type="text"],input[type="radio"],input[type="checkbox"],select,textarea,a',$('form[id="inputForm"]')).attr('disabled',true); 
			//	$("#btnCancel").attr("disabled",null);
			//}
			
			$("#name").focus();
			$("#inputForm").validate({
				submitHandler: function(form){
					var flag = -1; //表示是否存为空的必填项
					$("#productInfo input[class='required']").each(function(){
						if($(this).val()==""){
							flag=0;
						}
					});
					if(flag==0){
						showJBoxMess("商品信息未填写完整","error");
						showInfo(0);
						return;
					}
					if($("#logoUrl").val()==""){
						showJBoxMess("请上传商品封面.","error");
						showInfo(0);
						return;
					}
					$("#saleInfo input[class='required']").each(function(){
						if($(this).val()==""){
							flag=1;
						}
					});
					if(flag==1){
						showJBoxMess("销售信息未填写完整","error");
						showInfo(1);
						return;
					}
					//if(trim(remarksEditor.html())==""){
					//	showJBoxMess("请输入商品简介.","error");
					//	return;
					//}
					$("#remarks").val(remarksEditor.html());
					loading('正在提交，请稍等...');
					form.submit();
				},
				errorContainer: "#messageBox",
				errorPlacement: function(error, element) {
					$("#messageBox").text("输入有误，请先更正。");
					if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
						error.appendTo(element.parent().parent());
					} else {
						error.insertAfter(element);
					}
				}
			});
		});
		
		function showPhoto(path){
			$("#logoUrl").val(path);
			$("#cutPhoto").css("display", "block");
			var imageSrc = '${ctx}/download?filePath='+path;
			$("#cutPhoto").attr("src", imageSrc);
		}
		
		function changeClassify(obj){
			if($(obj).val()==""){
				$("#classifyIdList").html("");
				$(".select2-choices").find(".select2-search-choice").remove();
			}else{
				$("#classifyIdList").html("");
				$(".select2-choices").find(".select2-search-choice").remove();
				var parentId = $(obj).val();
				//异步保存活动
				$.ajax({
					type: 'get',
					url: '${ctx}/ivm/product/classifyChildList',
					data: 'parentId='+parentId,
					dataType: 'json',
					success: function(data){
						if(data!=null && data.length>0){
							for(var i=0; i<data.length; i++){
								var item = data[i];
	           					$("#classifyIdList").append("<option value='"+item.id+"'>"+item.name+"</option>");  
	           				}
						}
						$("select").select2();
					},
					failure: function(){
					}				
				});
			}
		}
		
		function setDefSupplierOption(){
			var supplierIdList = $("#supplierIdList");
			$("#defaultSupplier").html("");
			$("#defaultSupplier").append("<option value=''>请选择</option>");
			$("#supplierIdList").find("option:checked").each(function (){
				var option = $(this);
				$("#defaultSupplier").append("<option value='"+option.val()+"'>"+option.text()+"</option>");
			});
			$("#defaultSupplier").select2();
		}
		//改变商品规格_单位，重新拼装规格spec
		function changeUnit(obj){
			if($(obj).val()!=""){
				var name = $(obj).find("option:selected").text();
				var number = $("input[id='specNum']").val();
				var spec = number+name;
				$("input[id='spec']").val(spec);
			}else{
				$("input[id='spec']").val("");
			}
		}
		//改变商品规格_数量，重新拼装规格spec
		function changeNum(obj){
			var number = $(obj).val();
			var name = $("#specUnit option:selected").text();
			var spec = number+name;
			$("input[id='spec']").val(spec);
		}
		//切换模块：商品信息、销售信息、管理信息
		function showInfo(type){
			$("#productModul li").each(function(){
				$(this).removeClass("active");
			});
			$("#productModul li").eq(type).addClass("active");
			$("#productInfo").hide();
			$("#saleInfo").hide();
			$("#managerInfo").hide();
			$("#relationInfo").hide();
			$("#relation_title").hide();
			if($pro_property==1){
				$("#relation_title").show();
			}
			if(type==0){
				$("#productInfo").show();
			}else if(type==1){
				$("#saleInfo").show();
			}else if(type==3){
				$("#relationInfo").show();
			}else{
				$("#managerInfo").show();
			}
		}
		//切换库存状态
		function checkStockState(obj){
			var type = $(obj).val();
			showOrHideStock(type);
		}
		//真实库存三个参数的显示与隐藏
		function showOrHideStock(type){
			if(type == 1){//真实库存
				$("div[id='parameter']").each(function(){
					$(this).show();
				});
			}else{//虚拟库存
				$("div[id='parameter']").each(function(){
					$(this).hide();
				});
				$("#normalNum").val(0);
				$("#fillNum").val(0);
				$("#lackNum").val(0);
			}
		}
		//切换商品属性
		function checkProperty(obj){
			var type = $(obj).val();
			showOrHideProperty(type);
			var num = $(".product").length;
			if(type=="0" && num>0){
				$("input[id='delFlag']").each(function(){
					$(this).val("1");
				});
			}
		}
		function showOrHideProperty(type){
			if(type == 0){//实体商品
				$("#relation_title").hide();
			}else{//虚拟商品
				$("#relation_title").show();
			}
			$pro_property = type;
		}
		//虚拟商品添加实体商品
		function addProduct(parentId){
			var num = $(".product").length;
			var html = "<tr class=\"product\"><td>";
				html += "<input type=\"hidden\" id=\"delFlag\" name=\"relationList["+num+"].delFlag\" value=\"0\" />";
				html += "<input type=\"hidden\" id=\"relationId\" name=\"relationList["+num+"].id\" value=\"\"/>";
				html += "<input type=\"hidden\" id=\"relationParentId\" name=\"relationList["+num+"].parent.id\" value=\""+parentId+"\"/>";
				html += "<input type=\"hidden\" id=\"relationProductId\" name=\"relationList["+num+"].product.id\" value=\"\"/>";
				html += "<input type=\"text\" id=\"relationName\" name=\"relationList["+num+"].product.name\" value=\"\" class=\"required\" placeholder=\"请输入商品编号或商品名称\" onchange=\"checkProduct(this)\"/>";
				html += "</td>";
				html += "<td style=\"text-align:center; vertical-align: middle;\">";
				html += "<input name=\"relationList["+num+"].num\" value=\"\" htmlEscape=\"false\" maxlength=\"20\" min=\"1\" class=\"digits\"/>";
				html += "</td>";
				html += "<td style=\"text-align:center; vertical-align: middle;\">";
				html += "<input id=\"btnDel\" class=\"btn\" type=\"button\" value=\"删除\" onclick=\"delProduct\(this, "+num+")\"/>";
				html += "</td></tr>";
			$(".products").append(html);
		}
		//删除关联商品
		function delProduct(obj, index){
			top.$.jBox.confirm("确认要删除该商品吗",'系统提示',function(v,h,f){
				if(v=='ok'){
					if($(obj).parent().parent().find("input[id='relationId']").val()==""){
						$(obj).parent().parent().remove();
					}else{
						$("#delFlag:eq("+index+")").val("1");
						$("input[id='delFlag']:eq("+index+")").val("1");
						$(obj).parent().parent().hide();
					}
				}
			},{buttonsFocus:1});
		}
		//检查关联的商品是否存在
		function checkProduct(obj){
			if($(obj).val()!=""){
				//异步保存活动
				$.ajax({
					type: 'post',
					url: '${ctx}/ivm/inventory/checkProductCode',
					data: 'merchantId=${merchantId}&code='+$(obj).val(),
					dataType: 'json',
					success: function(data){
						if(data.status==200){
							var product = data.result;
							var isExists = false;
				        	$("input[id='relationProductId']").each(function(){
				        		if($(this).val()==product.id){
				        			showJBoxMess("商品"+$(obj).val()+"已存在，请重新输入！","error");
				        			isExists=true;
				        		}
				        	});
				        	if(isExists){
				        		$(obj).val("");
					        	return;
				        	} 
							$(obj).val(product.name);
							$(obj).parent().find("input[id='relationProductId']").val(product.id);
							$(obj).parent().find("input[id='relationParentId']").val($("#id").val());
						}else{
							showJBoxMess(data.message,"error");
						}
					},
					failure: function(){
						showJBoxMess("操作失败","error");
					}				
				});
			}
		}
	</script>
</head>
<body>
	<ul class="nav nav-tabs">
		<li><a href="${ctx}/ivm/product/">商品列表</a></li>
		<li class="active"><a href="${ctx}/ivm/product/form?id=${product.id}"><shiro:hasPermission name="ivm:product:edit">${not empty product.id?'修改':'添加'}</shiro:hasPermission>商品</a></li>
	</ul>
	<form:form id="inputForm" modelAttribute="product" action="${ctx}/ivm/product/save" method="post" class="form-horizontal">
		<input type="hidden" id="searchParam" name="searchParam" value="${searchParam }"/>
		<input type="hidden" id="oneClassify" name="oneClassify" value="${oneClassify }"/>
		<input type="hidden" id="twoClassify" name="twoClassify" value="${twoClassify }"/>
		<input type="hidden" id="sortName" name="sortName" value="${sortName }"/>
		<input type="hidden" id="orderBy" name="orderBy" value="${orderBy }"/>
		<input type="hidden" id="type" name="type" value="${type }"/>
		<form:hidden path="id"/>
		<form:hidden path="code"/>
		<tags:message content="${message}"/>
		
		<ul class="nav nav-tabs breadcrumb form-search" id="productModul">
			<li class="active"><a onclick="showInfo(0)">商品信息</a></li>
			<li><a onclick="showInfo(1)">销售信息</a></li>
			<li><a onclick="showInfo(2)">管理信息</a></li>
			<li id="relation_title"><a onclick="showInfo(3)">商品礼包</a></li>
		</ul>
		<div id="productInfo">
			<div class="control-group">
				<label class="control-label"><span class="color-red font-size20">*</span>商品类型:</label>
				<div class="controls">
					<form:radiobuttons path="proProperty" items="${fns:getDictList('pro_property')}" itemLabel="label" itemValue="value" htmlEscape="false" onclick="checkProperty(this)" class="required" />
				</div>
			</div>
			<div class="control-group">
				<label class="control-label"><span class="color-red font-size20">*</span>商品名称:</label>
				<div class="controls">
					<input id="oldName" name="oldName" type="hidden" value="${product.name}">
					<form:input path="name" htmlEscape="false" maxlength="200" class="required"/>
				</div>
			</div>
			<div class="control-group">
				<label class="control-label"><span class="color-red font-size20">*</span>副标题:</label>
				<div class="controls">
					<form:input path="assisTitle" htmlEscape="false" maxlength="200" cssStyle="width: 450px;" class="input-xxlarge measure-input valid"/>
				</div>
			</div>
			<!-- div class="control-group">
				<label class="control-label"><span class="color-red font-size20">*</span>商品规格:</label>
				<div class="controls">
					<form:input path="spec" htmlEscape="false" maxlength="200" class="required"/>
				</div>
			</div -->
			<div class="control-group">
				<label class="control-label"><span class="color-red font-size20">*</span>商品图片:</label>
				<div class="controls">
					<form:hidden path="logoUrl" />
					<div class="photo" style="width:149px; height:84px;">
						<c:if test="${product.logoUrl!=null && product.logoUrl!=''}">
							<img id="cutPhoto" src="${ctx}/download?filePath=${product.logoUrl }" style="width:149px; height:84px;" />
						</c:if>
						<c:if test="${product.logoUrl==null || product.logoUrl==''}">
							<img id="cutPhoto" src="" style="width:149px; height:84px;" />
						</c:if>
					</div>
					<a href="javascript:" class="btn" id="cutPhotoUpload">上传图片</a>
				</div>
			</div>
			<div class="control-group">
				<label class="control-label">购买须知:</label>
				<div class="controls">
					<form:textarea path="shouldKnow" htmlEscape="false" rows="4" maxlength="200" class="input-xxlarge"/>
					<br/><span style="color: red;">(提示：如需换行请输入&lt;br/&gt;)</span>
				</div>
			</div>
			<div class="control-group">
				<label class="control-label">商品简介:</label>
				<div class="controls">
					<form:textarea path="remarks" htmlEscape="false" rows="4" maxlength="200" class="input-xxlarge" style="height: 320px;"/>
				</div>
			</div>
			<!--<div class="control-group">
				<label class="control-label"><span class="color-red font-size20">*</span>一级分类:</label>
				<div class="controls">
					<form:select id="classify" path="classify.id" class="required" onchange="changeClassify(this)">
						<form:option value="" label="请选择"/>
						<form:options items="${fns:getClassifyOneList()}" itemLabel="name" itemValue="id" htmlEscape="false"/>
					</form:select>
				</div>
			</div>
			<div class="control-group">
				<label class="control-label"><span class="color-red font-size20">*</span>二级分类:</label>
				<div class="controls towClassify">
					<form:select path="classifyIdList" class="required">
						<form:options items="${fns:getClassifyTwoList(product.classify.id)}" itemValue="id" itemLabel="name" htmlEscape="false"/>
					</form:select>
				</div>
			</div>-->
			<div class="control-group">
				<label class="control-label"><span class="color-red font-size20">*</span>分类:</label>
				<div class="controls towClassify">
					<form:select path="classifyIdList" class="required">
						<form:options items="${fns:getAllClassifyTwoList()}" itemValue="id" itemLabel="name" htmlEscape="false"/>
					</form:select>
				</div>
			</div>
			<div class="control-group">
				<label class="control-label"><span class="color-red font-size20">*</span>状态:</label>
				<div class="controls">
					<form:radiobuttons path="openState" items="${fns:getDictList('open_state')}" itemLabel="label" itemValue="value" htmlEscape="false" class="required" />
				</div>
			</div>
		</div>
		<div id="saleInfo">
			<div class="control-group">
				<label class="control-label"><span class="color-red font-size20">*</span>原价:</label>
				<div class="controls">
					<form:input path="originalPrice" htmlEscape="false" class="required number decimal"/>
				</div>
			</div>
			<div class="control-group">
				<label class="control-label"><span class="color-red font-size20">*</span>现价:</label>
				<div class="controls">
					<form:input path="price" htmlEscape="false" class="required number decimal"/>
				</div>
			</div>
			<div class="control-group">
				<label class="control-label"><span class="color-red font-size20">*</span>销售单位:</label>
				<div class="controls">
					<form:select id="productUnit" path="productUnit.id" class="required">
						<form:option value="" label="请选择"/>
						<form:options items="${fns:getUnitList('1')}" itemLabel="name" itemValue="id" htmlEscape="false"/>
					</form:select>
				</div>
			</div>
			<div class="control-group">
				<label class="control-label"><span class="color-red font-size20">*</span>商品规格:</label>
				<div class="controls">
					<form:hidden path="spec"/>
					<form:input path="specNum" htmlEscape="false" maxlength="200" min="1" class="input-small required digits" style="width:82px" onchange="changeNum(this)"/>
					<form:select id="specUnit" path="specUnit.id" class="input-small required" onchange="changeUnit(this)">
						<form:option value="" label="请选择"/>
						<form:options items="${fns:getUnitList('2')}" itemLabel="name" itemValue="id" htmlEscape="false"/>
					</form:select>
				</div>
			</div>
			<div class="control-group">
				<label class="control-label">起购数量:</label>
				<div class="controls">
					<form:input path="startSaleNum" htmlEscape="false" class="digits" min="1" />
				</div>
			</div>
			<div class="control-group">
				<label class="control-label">限购数量:</label>
				<div class="controls">
					<form:input path="purchaseNum" htmlEscape="false" class="digits" />
				</div>
			</div>
			<div class="control-group">
				<label class="control-label"><span class="color-red font-size20">*</span>是否支持到付:</label>
				<div class="controls">
					<form:radiobuttons path="toPay" items="${fns:getDictList('yes_no')}" itemLabel="label" itemValue="value" htmlEscape="false" class="required" />
				</div>
			</div>
			<div class="control-group">
				<label class="control-label"><span class="color-red font-size20">*</span>购物车有效时间:</label>
				<div class="controls">
					<form:input path="effectiveTime" htmlEscape="false" maxlength="200" class="digits number required input-small" min="1" /> &nbsp;小时
				</div>
			</div>
		</div>
		<div id="managerInfo">
			<div class="control-group">
				<label class="control-label">进价:</label>
				<div class="controls">
					<form:input path="tradePrice" htmlEscape="false" class="number decimal"/>
				</div>
			</div>
			<!-- 2015-04-16注释
			<div class="control-group">
				<label class="control-label">市场价跟价对象:</label>
				<div class="controls">
					<form:input path="marketPriceTarget" htmlEscape="false"/>
				</div>
			</div>
			<div class="control-group">
				<label class="control-label">摸价周期:</label>
				<div class="controls">
					<form:input path="collectPriceCycle" htmlEscape="false" maxlength="200" class="digits number input-small"/> &nbsp;天
				</div>
			</div>
			 -->
			<div class="control-group">
				<label class="control-label">供应商:</label>
				<div class="controls towClassify">
					<form:select path="supplierIdList" onchange="setDefSupplierOption()">
						<form:options items="${fns:getSupplierList()}" itemValue="id" itemLabel="name" htmlEscape="false"/>
					</form:select>
				</div>
			</div>
			<div class="control-group">
				<label class="control-label">定价标签:</label>
				<div class="controls">
					<form:input path="" htmlEscape="false"/>
				</div>
			</div>
			<div class="control-group">
				<label class="control-label">控制标签:</label>
				<div class="controls">
					<form:input path="" htmlEscape="false"/>
				</div>
			</div>
			<div class="control-group">
				<label class="control-label">分类标签:</label>
				<div class="controls">
					<form:input path="" htmlEscape="false"/>
				</div>
			</div>
			<div class="control-group">
				<label class="control-label">库存状态:</label>
				<div class="controls">
					<form:radiobuttons path="stockState" items="${fns:getDictList('stock_type')}" itemLabel="label" itemValue="value" htmlEscape="false" onclick="checkStockState(this)"/>
				</div>
			</div>
			<div class="control-group" id="parameter">
				<label class="control-label">正常数量:</label>
				<div class="controls">
					<form:input path="normalNum" htmlEscape="false" class="digits" min="1" />
				</div>
			</div>
			<div class="control-group" id="parameter">
				<label class="control-label">补货数量:</label>
				<div class="controls">
					<form:input path="fillNum" htmlEscape="false" class="digits" min="1" />
				</div>
			</div>
			<div class="control-group" id="parameter">
				<label class="control-label">短缺数量:</label>
				<div class="controls">
					<form:input path="lackNum" htmlEscape="false" class="digits" min="1" />
				</div>
			</div>
			<div class="control-group">
				<label class="control-label">采购说明:</label>
				<div class="controls">
					<form:textarea path="purchaseDesc" htmlEscape="false" rows="4" maxlength="200" class="input-xxlarge"/>
					<br/><span style="color: red;">(提示：如需换行请输入&lt;br/&gt;)</span>
				</div>
			</div>
		</div>
		<div id="relationInfo">
			<label class="control-label"></label>
			<input id="btnAdd" class="btn" type="button" value="添加" onclick="addProduct('${product.id}')"/>
			<div class="control-group" style="padding-left: 160px;">
				<table id="contentTable" class="table table-striped table-bordered table-condensed" style="margin-top: 10px; margin-bottom: 0px; width: 600px;">
					<thead>
						<tr>
							<th style="text-align:center;width:150px;">商品名称</th>
							<th style="text-align:center;width:150px;">数量</th>
							<th style="text-align:center;width:150px;">操作</th>
						</tr>
					</thead>
					<tbody class="products">
						<c:if test="${fn:length(product.relationList)>0}">
						<c:forEach items="${product.relationList}" var="relation" varStatus="vs">
						<tr class="product">
							<td>
								<input type="hidden" id="relationId" name="relationList[${vs.index }].id" value="${relation.id }"/>
								<input type="hidden" id="delFlag" name="relationList[${vs.index }].delFlag" value="${relation.delFlag }" />
								<input type="hidden" id="relationParentId" name="relationList[${vs.index }].parent.id" value="${relation.parent.id }"/>
								<input type="hidden" id="relationProductId" name="relationList[${vs.index }].product.id" value="${relation.product.id }"/>
								<input id="relationName${vs.index }" name="relationList[${vs.index }].product.name" type="text" class="required" value="${relation.product.name }" placeholder="请输入商品编号或商品名称" onchange="checkProduct(this)"/>
							</td>
							<td style="text-align:center; vertical-align: middle;">
								<input name="relationList[${vs.index }].num" value="${relation.num }" htmlEscape="false" maxlength="20" min="1" class="digits"/>
							</td>
							<td style="text-align:center; vertical-align: middle;">
								<input id="btnDel" class="btn" type="button" value="删除" onclick="delProduct(this, ${vs.index })"/>
							</td>
						</tr>
						</c:forEach>
						</c:if>
					</tbody>
				</table>
			</div>
		</div>
		<div class="form-actions">
			<shiro:hasPermission name="ivm:product:edit">
				<input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存"/>&nbsp;
				<c:if test="${product.id!=null && product.id!=''}">
				<input id="btnDel" class="btn btn-primary" type="button" value="删除" onclick="return confirmx('确认要删除该商品信息吗？', '${ctx}/ivm/product/delete?id=${product.id}&searchParam=${searchParam}&oneClassify=${oneClassify}&twoClassify=${twoClassify}&sortName=${sortName}&orderBy=${orderBy}&type=${type}')"/>&nbsp;
				</c:if>
			</shiro:hasPermission>
			<input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)"/>
		</div>
	</form:form>
</body>
</html>
